<?php
/**
 * 用户登录，注册
 */
namespace app\api\modules\v1\market\controllers;

use app\api\modules\v1\market\models\DataFormat;
use app\api\modules\v1\market\models\Group_z;
use yii\web\Controller;
use app\api\components\ApiController;
use Yii;
use app\models\base\User;
use app\api\modules\v1\market\models\AppUser;
use app\models\base\Role;
use app\models\base\BankAccount;
use app\api\modules\v1\market\models\Header;
use app\models\HttpCurl;
use app\api\modules\v1\market\models\Message;

class DefaultController extends ApiController
{
	public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
    }

    /**
     * [登录]
     * @return [type] [description]
     */
    public function actionLogin()
    {

        $login_account = Yii::$app->request->post('login_account');
        $password = Yii::$app->request->post('password');

        if ($login_account === null) return parent::sendMessageJson('登录帐号不能为空');
        if ($password === null) return parent::sendMessageJson('密码不能为空');

        $member = User::find()->where(['phone'=>$login_account,'password'=>md5(md5($password)),'disabled'=>0])->asArray()->one();
        $member['sdktoken'] = $member['token'];
        if(!$member) return parent::sendMessageJson('用户名或密码错误');
        //获取用户详细信息
        $memberInfo = new AppUser();
        $member['token'] = $memberInfo->getUserToken($member);
        // var_dump($member);exit;
        return ['code'=>parent::$CODE_SUC, 'msg'=>'登录成功', 'data'=>$member];
    }

    /**
     * [登录首页]
     * @return [type] [description]
     */
    public function actionList()
    {
    	$user_id = Yii::$app->request->post('user_id');
    	$token = Yii::$app->request->post('token');
    	//验证token
        $verifyToken = new AppUser();
        if($verifyToken->verifyAuth($user_id,$token) == false) return parent::sendMessageJson('用户认证不通过');
        //市场信息,银行信息,统计信息
        $list = AppUser::getInfo();
        //个人信息
        $ownlist = AppUser::getOwnInfo($user_id);
        return ['code'=>parent::$CODE_SUC, 'msg'=>'数据获取成功', 'data'=>['list'=>$list,'ownlist'=>$ownlist]];
        
    }


    /**
     * 踢人出群
     */
    public function actionKick()
    {
        $project_id = \yii::$app->request->post('project_id');
        $kick_id = \yii::$app->request->post('kick_id');
        $kick_id = \app\api\modules\v1\market\models\DataFormat::strToArr($kick_id);
        if(!empty($project_id)){
            Group_z::Kick($project_id,$kick_id);
        }

    }

    public function actionInvite()
    {
        $project_id = \yii::$app->request->post('project_id');
        $kick_id = \yii::$app->request->post('kick_id');
        $kick_id = \app\api\modules\v1\market\models\DataFormat::strToArr($kick_id);
        if(!empty($project_id)){
            Group_z::invite($project_id,$kick_id);
        }
    }

    public function actionKi()
    {
        $project_id = \yii::$app->request->post('project_id');
        $kick_id = \app\api\modules\v1\market\models\DataFormat::strToArr(\yii::$app->request->post('invite_id'));
        Group_z::invite_before_kick($project_id,$kick_id);
    }


    public function actionRole()
    {
        $role = Role::find()->where(['disabled'=>0])->asArray()->all();
        return parent::sendMessageJson(Message::SUCCESS,self::$CODE_SUC,['role_list'=>$role]);
    }

    /**
     * [actionRegister 注册]
     * @return [type] [description]
     */
    public function actionRegister()
    {
        $post = Yii::$app->request->post();
        //将post数据格式化
        $post = self::getpost($post);
        // var_dump($post);exit;
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if($post['register_code'] == \yii::$app->params['register_code']){
                unset($post['register_code']);
                $user = new User;
                $user->attributes = $post;
                $user->save();
                $BankAccount = new BankAccount;
                $BankAccount->user_id = $user->user_id;
                $BankAccount->create_time = time();
                $BankAccount->start_time = time();
                $BankAccount->save();
                //生成云通信id
                $info = self::setToken($user -> phone,$user-> name);
                //添加用户token和accid
                if(!empty($info)){
                    $model = User::findOne($user -> user_id);
                    if(!empty($model)){
                        $model -> token = $info['token'];
                        $model -> accid = $info['accid'];
                        $model -> save();
                    }
                }else{
                    throw new \Exception('创建云信id失败');
                }

                $transaction->commit();
                return parent::sendMessageJson('注册成功',self::$CODE_SUC);
            }else{
                throw new \Exception('验证码错误,请核对后再注册');
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            return parent::sendMessageJson($e->getMessage());
        }
    }

    public static function getpost($post)
    {
        $post['password'] = md5(md5($post['password']));
        $post['birthday'] = strtotime($post['birthday']);
        $post['create_time'] = time();
        $post['start_time'] = time();
        return $post;
    } 

    public static function setToken($accid='',$name='')
    {
        $appsecret = \yii::$app->params['appsecret'];
        $url       = 'https://api.netease.im/nimserver/user/create.action';
        $nonce     = mt_rand(1,9999999);
        $time      = time();
        $appkey    = \yii::$app->params['appkey'];

        $CheckSum  = Header::getCheckSum($appsecret,$nonce,$time);
        $res = HttpCurl::request($url,'POST',
            [
                'accid' => $accid,
                'name' => $name,
            ],
            [
//                'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
                'Nonce:'.$nonce,
                'CurTime:'.$time,
                'CheckSum:'.$CheckSum,
                'AppKey:'.$appkey
            ]
        );
        if(!empty($res[0])){
            $obj = json_decode($res[0]);
            if(!empty($obj->info)){
                return ['token'=>json_decode($res[0])->info->token,'accid'=>json_decode($res[0])->info->accid];
            }
            return [];
        }
        return [];
    }


}
